<template>
	<view class="multi-level-picker">
		<!-- 触发区域 -->
		<view class="picker-trigger" @click="handleTriggerClick">
			<view v-if="selectedText.length" class="selected-text">
				<text v-for="(item, index) in selectedText" :key="index">
					{{ item }}
					<text v-if="index < selectedText.length - 1" class="separator">/</text>
				</text>
			</view>
			<view v-else class="placeholder">{{ placeholder }}</view>
		</view>

		<!-- 弹窗遮罩 -->
		<view v-if="showPopup" class="picker-mask" @click="handleCancel"></view>

		<!-- 弹窗主体 -->
		<view v-if="showPopup" class="picker-popup">
			<view class="popup-header">
				<text class="cancel-btn" @click="handleCancel">取消</text>
				<text class="popup-title">{{ popupTitle }}</text>
				<text
					v-if="mode !== 'single'"
					class="confirm-btn"
					@click="handleConfirm"
					>确认</text
				>
			</view>

			<!-- 动态渲染层级 -->
			<view class="picker-content">
				<ScrollSelectList
					v-for="(level, index) in visibleLevels"
					:key="index"
					class="level-list"
					:list="level.data"
					:modelValue="level.selected"
					:height="listHeight"
					:hasMore="level.hasMore"
					:loading="level.loading"
					:emptyText="getEmptyText(index)"
					@update:modelValue="item => handleLevelChange(index, item)"
					@load-more="() => handleLoadMore(index)"
				/>
			</view>
		</view>
	</view>
</template>

<script>
import ScrollSelectList from './ScrollSelectList.vue';

export default {
	name: 'MultiLevelPicker',
	components: { ScrollSelectList },
	emits: ['confirm', 'cancel', 'customClick'],
	props: {
		dataSource: {
			type: Array,
			required: true,
			default: () => [],
		},
		selectedValue: {
			type: [Object, Array],
			default: null,
		},
		popupTitle: {
			type: String,
			default: '请选择',
		},
		placeholder: {
			type: String,
			default: '请选择',
		},
		listHeight: {
			type: String,
			default: '500rpx',
		},
		mode: {
			type: String,
			default: 'address', // 'address' | 'multi' | 'single'
			validator: v => ['address', 'multi', 'single'].includes(v),
		},
		// 最大层级
		maxLevel: {
			type: Number,
			default: 5,
		},
	},
	data() {
		return {
			showPopup: false,
			levels: [],
			selectedText: [],
			selectedValues: [],
		};
	},
	computed: {
		visibleLevels() {
			if (this.mode === 'address') {
				// 地址模式
				// 三列 省 市 区 
				// return this.levels.slice(0, 3);
				// 两列 省 市
				// return this.levels.slice(0, 2);
				// 切换成通用的 可配置的
				return this.levels.slice(0, this.maxLevel);
			} else if (this.mode === 'single') {
				return this.levels.slice(0, 1);
			} else {
				return this.levels.slice(0, this.maxLevel);
			}
		},
	},
	watch: {
		dataSource: {
			handler(newVal) {
				this.initLevels(newVal);
			},
			immediate: true,
		},
		selectedValue: {
			handler(newVal) {
				if (newVal) {
					this.initWithSelectedValue(newVal);
				}
			},
			immediate: true,
		},
	},
	methods: {
		handleTriggerClick() {
			this.showPopup = true;
			this.$emit('customClick');
		},

		initLevels(data) {
			if (this.mode === 'single') {
				this.levels = [{ data, selected: null, loading: false, hasMore: true }];
			} else {
				// multi 和 address 模式都统一处理
				this.levels = [{ data, selected: null, loading: false, hasMore: true }];
				
				// 如果是address模式并且有默认选中值，则初始化子级数据
				if (this.mode === 'address' && this.selectedValue && Array.isArray(this.selectedValue)) {
					this.initAddressLevels();
				}
			}
		},
		
		// 初始化地址模式的层级数据
		initAddressLevels() {
			if (!this.selectedValue || !Array.isArray(this.selectedValue)) return;
			
			let currentData = this.dataSource;
			for (let i = 0; i < this.selectedValue.length; i++) {
				const selectedItem = currentData.find(item => item.value === this.selectedValue[i].value);
				if (selectedItem && selectedItem.children) {
					currentData = selectedItem.children;
					if (i + 1 < this.levels.length) {
						this.levels[i + 1].data = currentData;
					} else {
						this.levels.push({
							data: currentData,
							selected: null,
							loading: false,
							hasMore: true
						});
					}
				} else {
					break;
				}
			}
		},

		initWithSelectedValue(selected) {
			if (!selected) return;
			
			// 单选模式
			if (this.mode === 'single' && selected.value) {
				this.levels[0].selected = selected;
				this.selectedText = [selected.text];
				this.selectedValues = [selected.value];
				return;
			}
			
			// 地址或多级模式
			if (Array.isArray(selected)) {
				// 根据选中的值构建层级结构
				let currentData = this.dataSource;
				for (let i = 0; i < Math.min(selected.length, this.maxLevel); i++) {
					if (this.levels[i]) {
						const selectedItem = currentData.find(item => item.value === selected[i].value);
						if (selectedItem) {
							this.levels[i].selected = selectedItem;
							this.levels[i].data = currentData;
							
							if (selectedItem.children && selectedItem.children.length > 0) {
								currentData = selectedItem.children;
								if (i + 1 >= this.levels.length) {
									this.levels.push({
										data: currentData,
										selected: null,
										loading: false,
										hasMore: true
									});
								} else {
									this.levels[i + 1].data = currentData;
								}
							} else {
								break;
							}
						}
					}
				}
				
				this.updateSelectedResult();
			}
		},

		clearSelection() {
			this.selectedText = [];
			this.selectedValues = [];
			// 重置所有层级的选中状态
			this.levels.forEach(level => {
				level.selected = null;
			});
			// 保留第一级数据，清空其他层级
			if (this.levels.length > 1) {
				this.levels = [this.levels[0]];
			}
		},

		getEmptyText(levelIndex) {
			if (levelIndex === 0) return '暂无数据';
			const prev = this.levels[levelIndex - 1];
			if (!prev || !prev.selected) {
				return '请先选择上级';
			}
			return '暂无数据';
		},

		handleLevelChange(levelIndex, item) {
			// 单级模式：点击即确认
			if (this.mode === 'single') {
				this.showPopup = false;
				const text = item?.text || '';
				const value = item?.value;
				this.$emit('confirm', {
					text: [text],
					value: [value],
					items: [item],
				});
				return;
			}

			// 更新当前层级选中项
			this.levels[levelIndex].selected = item;
			
			// 清除后续层级
			this.levels.splice(levelIndex + 1);

			// 如果有子级数据，添加新的层级
			if (item && item.children && item.children.length > 0) {
				this.levels.push({
					data: item.children,
					selected: null,
					loading: false,
					hasMore: true,
				});
			}

			this.updateSelectedResult();
		},

		handleLoadMore(levelIndex) {
			const level = this.levels[levelIndex];
			if (level.loading || !level.hasMore) return;
			level.loading = true;
			// 模拟异步加载，实际使用中应替换为真实API调用
			setTimeout(() => {
				level.loading = false;
				level.hasMore = false;
			}, 800);
		},

		updateSelectedResult() {
			this.selectedText = this.levels
				.map(l => l.selected?.text)
				.filter(Boolean);
			this.selectedValues = this.levels
				.map(l => l.selected?.value)
				.filter(Boolean);
		},

		handleConfirm() {
			if (this.selectedValues.length === 0) {
				uni.showToast({ title: '请至少选择一项', icon: 'none', duration: 1500 });
				return;
			}
			this.showPopup = false;
			const selectedItems = this.levels.map(l => l.selected).filter(Boolean);
			this.$emit('confirm', {
				text: this.selectedText,
				value: this.selectedValues,
				items: selectedItems,
			});
		},

		handleCancel() {
			this.showPopup = false;
			this.$emit('cancel');
		},
	},
};
</script>

<style lang="scss" scoped>
/* 触发区域 */
.picker-trigger {
	width: 100%;
	padding: 24rpx 0;
}

.selected-text {
	font-size: 30rpx;
	color: #333;
}

.placeholder {
	font-size: 30rpx;
	color: #999;
}

.separator {
	margin: 0 10rpx;
	color: #ccc;
}

/* 弹窗 */
.picker-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 998;
}

.picker-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	z-index: 999;
}

.popup-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	border-bottom: .0625rem solid #eee;
}

.cancel-btn,
.confirm-btn {
	font-size: 32rpx;
	padding: 10rpx 20rpx;
}

.cancel-btn {
	color: #666;
}

.confirm-btn {
	color: #1677ff;
	font-weight: bold;
}

.popup-title {
	font-size: 34rpx;
	color: #333;
	font-weight: bold;
}

/* 选择内容区 */
.picker-content {
	display: flex;
	width: 100%;
	overflow-x: auto;
}

.level-list {
	flex: 1;
	min-width: 200rpx;
	border-right: .0625rem solid #f5f5f5;
	&:last-child {
		border-right: none;
	}
}
</style>